package com.rick.awarenessdemo.util

import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import androidx.annotation.RequiresPermission
import com.amap.api.services.core.PoiItem
import com.blankj.utilcode.util.GsonUtils
import com.huawei.hmf.tasks.OnFailureListener
import com.huawei.hmf.tasks.OnSuccessListener
import com.huawei.hms.kit.awareness.Awareness
import com.huawei.hms.kit.awareness.barrier.BarrierQueryRequest
import com.huawei.hms.kit.awareness.barrier.BarrierUpdateRequest
import com.huawei.hms.kit.awareness.barrier.LocationBarrier
import com.rick.awarenessdemo.BuildConfig
import com.rick.awarenessdemo.LocationBarrierReceiver

/**
 * 情景感知工具
 */
object AwarenessUtil {
    private const val ACTION = BuildConfig.APPLICATION_ID + ".LOCATION_BARRIER_RECEIVER_ACTION"

    /**
     * 设置地理围栏
     */
    @JvmStatic
    @RequiresPermission("android.permission.ACCESS_FINE_LOCATION")
    fun setLocationBarrier(
        context: Context,
        poiItem: PoiItem,
        onSuccessListener: OnSuccessListener<Void>,
        onFailureListener: OnFailureListener
    ) {
        val lat = MapUtil.gdLat2HwLat(poiItem.latLonPoint.latitude)
        val lon = MapUtil.gdLon2HwLon(poiItem.latLonPoint.longitude)
        LogUtil.log("addLocationBarrier $lat $lon")
        deleteBarrier(context, {
            context.registerReceiver(LocationBarrierReceiver(), IntentFilter(ACTION))
            Awareness.getBarrierClient(context).updateBarriers(
                BarrierUpdateRequest.Builder()
                    .addBarrier(
                        GsonUtils.toJson(poiItem),
                        LocationBarrier.stay(lat, lon, 1000.0, 1000),
                        PendingIntent.getBroadcast(
                            context,
                            1,
                            Intent(ACTION),
                            PendingIntent.FLAG_UPDATE_CURRENT
                        )
                    ).build()
            ).addOnSuccessListener {
                LogUtil.log("addLocationBarrier Success")
                onSuccessListener.onSuccess(it)
            }.addOnFailureListener {
                LogUtil.log("addLocationBarrier Fail ${it.message}")
                onFailureListener.onFailure(it)
            }
        }, {
            LogUtil.log("addLocationBarrier Fail ${it.message}")
            onFailureListener.onFailure(it)
        })
    }

    /**
     * 删除围栏
     */
    @JvmStatic
    fun deleteBarrier(
        context: Context,
        onSuccessListener: OnSuccessListener<Void>,
        onFailureListener: OnFailureListener
    ) {
        LogUtil.log("deleteBarrier")
        Awareness.getBarrierClient(context)
            .updateBarriers(BarrierUpdateRequest.Builder().deleteAll().build())
            .addOnSuccessListener {
                LogUtil.log("deleteBarrier Success")
                onSuccessListener.onSuccess(it)
            }.addOnFailureListener {
                LogUtil.log("deleteBarrier Fail ${it.message}")
                onFailureListener.onFailure(it)
            }
    }

    /**
     * 查询围栏
     */
    @JvmStatic
    fun queryLocationBarrier(
        context: Context,
        onSuccessListener: OnSuccessListener<PoiItem?>,
        onFailureListener: OnFailureListener
    ) {
        LogUtil.log("queryLocationBarrier")
        Awareness.getBarrierClient(context).queryBarriers(BarrierQueryRequest.all())
            .addOnSuccessListener { it ->
                LogUtil.log("queryLocationBarrier Success ${GsonUtils.toJson(it)}")
                try {
                    onSuccessListener.onSuccess(
                        if (it.barrierStatusMap.barrierLabels.toList().isNotEmpty()) {
                            GsonUtils.fromJson(
                                it.barrierStatusMap.barrierLabels.toList()[0],
                                PoiItem::class.java
                            )
                        } else {
                            null
                        }
                    )
                } catch (e: Exception) {
                    onFailureListener.onFailure(e)
                }
            }.addOnFailureListener {
                LogUtil.log("queryLocationBarrier Failure ${GsonUtils.toJson(it)}")
                onFailureListener.onFailure(it)
            }
    }
}